<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>登录</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <ion-item>
        <ion-label position="fixed">用户名</ion-label>
        <ion-input v-model="username"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="fixed">密码</ion-label>
        <ion-input v-model="password" type="password"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="fixed">验证码</ion-label>
        <ion-input v-model="verificationCode" style="flex: 1;"></ion-input>
        <img slot="end" :src="codeUrl" style="margin: 0; align-self: center;" class="login-code-img" @click="getCode" />
        <!--  -->
      </ion-item>
      <ion-button @click="handleLogin" expand="block">登录</ion-button>
    </ion-content>
  </ion-page>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  IonButton,
  IonContent,
  IonHeader,
  IonInput,
  IonItem,
  IonLabel,
  IonPage,
  IonToolbar,
  IonTitle,
} from "@ionic/vue";
import userApis from "@/apis/auth/user";
import { getCodeImg } from "@/apis/user";
import { setToken } from "@/utils/auth";
import axiosInst from "@/utils/request";
import { useRouter } from "vue-router";

const username = ref("");
const password = ref("");
const cacheKey = ref("");
const verificationCode = ref("");
// const generatedCode = ref("");
// const verificationCodeText = ref("获取验证码");
// const countdown = ref(0);
const loading = ref(false);
const { login } = userApis;
const codeUrl = ref("");
const router = useRouter();
// const route = useRoute();

function getCode() {
  axiosInst.request(getCodeImg(cacheKey.value)).then((res) => {
    codeUrl.value = res.data.captcha;
    cacheKey.value = res.data.cacheKey;
  });
}

const handleLogin = () => {
  loading.value = true;
  const loginParams = {
    username: username.value,
    password: password.value,
    code: verificationCode.value,
    cacheKey: cacheKey.value,
  };
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  axiosInst
    .request(login(loginParams))
    .then((res: any) => {
      setToken(res.access_token);
      router.push({ path: "/" }).catch(() => {});
    })
    .catch((error) => {
      // const errMsg = error.msg || error.error_description
      // if (errMsg) {
      //   ElMessage({ message: errMsg, type: 'error', duration: 3 * 1000 })
      // }
      loading.value = false;
      getCode();
    });
};


getCode()
</script>

<style>
/* 可添加登录页样式 */
ion-item {
  --padding-start: 16px !important;
  --inner-padding-end: 16px !important;
}

ion-label {
  padding-left: 0 !important;
}
</style>
